package com.fmy.mcsecurity.token.impl.jdbc;

import cn.hutool.core.util.StrUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.embedded.LinkedHashMapCacheBuilder;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName JetCacheKit
 * @Description TODO jetCache jdbc缓存方式
 * <p>
 * 目前只缓存一下两种常用数据，至于{@link com.fmy.mcsecurity.commons.tools.SecurityTool} 以及 {@link com.fmy.mcsecurity.token.model.RefreshStorage} 不常用，不缓存
 * </p>
 * @createTime 2020/6/2 16:58
 */
public class JetCacheJdbcKit {

    private static Integer CACHE_LIMIT = 5000;

    public static void setCacheLimit(Integer cacheLimit) {
        CACHE_LIMIT = cacheLimit;
    }

    /**
     * key :token
     * value :key
     */
    private static Cache<String, String> TOKEN_TO_USER_KEY;

    /**
     * key: user_key
     * value: Authentication to byte[]
     */
    private static Cache<String, byte[]> USER_KEY_BYTE;


    public static Cache<String, String> getToken() {
        if (TOKEN_TO_USER_KEY == null) {
            synchronized (JetCacheJdbcKit.class) {
                if (TOKEN_TO_USER_KEY == null) {
                    TOKEN_TO_USER_KEY = LinkedHashMapCacheBuilder.createLinkedHashMapCacheBuilder()
                            .limit(CACHE_LIMIT)
                            .buildCache();
                }
            }
        }
        return TOKEN_TO_USER_KEY;
    }

    public static Cache<String, byte[]> getBytes() {
        if (USER_KEY_BYTE == null) {
            synchronized (JetCacheJdbcKit.class) {
                if (USER_KEY_BYTE == null) {
                    USER_KEY_BYTE = LinkedHashMapCacheBuilder.createLinkedHashMapCacheBuilder()
                            .limit(CACHE_LIMIT)
                            .buildCache();
                }
            }
        }
        return USER_KEY_BYTE;
    }

    /**
     * 清除缓存
     *
     * @param userKey user_key
     * @param token   token
     */
    public static void clearAll(String userKey, String token) {
        if (StrUtil.isNotBlank(token)) {
            getToken().remove(token);
        }
        if (StrUtil.isNotBlank(userKey)) {
            getBytes().remove(userKey);
        }
    }

    /**
     * 修改 Authentication to byte[]
     *
     * @param userKey user_key
     * @param bytes   Authentication to byte[]
     */
    public static void updateBytes(String userKey, byte[] bytes) {
        getBytes().put(userKey, bytes);
    }
}
